window.onload = () => {
  const captureBtn = document.getElementById('captureBtn');
  if (!captureBtn) return;

  captureBtn.addEventListener('click', async () => {
    const area = document.documentElement; // 截图全页
    const scale = 1; // 缩放倍数，决定清晰度

    const canvas = await html2canvas(area, {
      scrollX: 0,
      scrollY: -window.scrollY,
      windowWidth: document.documentElement.scrollWidth,
      windowHeight: document.documentElement.scrollHeight,
      useCORS: true,
      scale: scale,
    });

    const ctx = canvas.getContext('2d');
    const now = new Date();
    const createdAt = now.toLocaleString();

    // UUID 生成函数（基于 URL）
    const url_name = location.href;
    const urlToUUID = async url => {
      const encoder = new TextEncoder();
      const data = encoder.encode(url);
      const hashBuffer = await crypto.subtle.digest('SHA-256', data);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      return `${hashHex.slice(0, 8)}-${hashHex.slice(8, 12)}-5${hashHex.slice(13, 16)}-8${hashHex.slice(17, 20)}-${hashHex.slice(20, 32)}`;
    };

    const uuid = await urlToUUID(url_name);

    // 角标样式参数
    const padding = 20 * scale;
    const boxWidth = 320 * scale;
    const boxHeight = 100 * scale;
    const x = padding;
    const y = canvas.height - boxHeight - padding;

    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    ctx.fillRect(x, y, boxWidth, boxHeight);

    ctx.fillStyle = '#000';
    ctx.font = `${14 * scale}px sans-serif`;
    ctx.fillText(`创建时间: ${createdAt}`, x + 10 * scale, y + 30 * scale);
    ctx.fillText(`UUID: ${uuid.slice(0, 8)}`, x + 10 * scale, y + 55 * scale);
    ctx.fillText(`访问量: 1234`, x + 10 * scale, y + 80 * scale);

    // 下载图片
    const imgData = canvas.toDataURL("image/png");
    const link = document.createElement('a');
    link.href = imgData;
    link.download = 'blog_card.png';
    link.click();
  });
};
